# -*- coding: UTF-8 -*-
import logging.config, os, sys
import xbmcgui, xbmcplugin #@UnresolvedImport

#REMOTE_DBG = False
## append pydev remote debugger
#if REMOTE_DBG:
#    # Make pydev debugger works for auto reload.
#    # Note pydevd module need to be copied in XBMC\system\python\Lib\pysrc
#    try:
#        import pysrc.pydevd as pydevd
#  # stdoutToServer and stderrToServer redirect stdout and stderr to eclipse console
#        pydevd.settrace('localhost', stdoutToServer=True, stderrToServer=True)
#    except ImportError:
#        sys.stderr.write("Error: " +
#            "You must add org.python.pydev.debug.pysrc to your PYTHONPATH.")
#        sys.exit(1)

configRoot = os.path.join(os.getcwd(), "resources", "logging.conf")
try:
  logging.config.fileConfig(configRoot)
except:
  logging.basicConfig()
  logging.getLogger('root').exception('Failed to initialize logging... falling back to defaults.')

# Add the lib dir to path  
sys.path.append(os.path.join(os.getcwd(), 'lib'))

from utils.pluginsupport import parseArguments, play, list
from tvshack import TVShackHandler

log = logging.getLogger("root")
log.info("calling with args: %s"%str(sys.argv))
params = parseArguments(sys.argv[2])

tvshackHandler = TVShackHandler()
if tvshackHandler.isAction(params):
  log.info("Running action")
  tvshackHandler.executeAction(params)
else:
  items, contentType, playable = tvshackHandler.handle(params)
  if playable:
    try:
      play(items)
    except Exception, e:
      log.exception("Failed to play items!")
      xbmcgui.Dialog().ok("Failed to play items", str(e))
  else:
    try:
      list(items)
    except Exception, e:
      log.exception("Script failed listing items!")
      xbmcgui.Dialog().ok("Failed to list items", str(e))
      xbmcplugin.endOfDirectory(int(sys.argv[1]), False, cacheToDisc=False)
    else: 
      if contentType:
        log.warn("Setting content type: " + str(contentType))
        xbmcplugin.setContent(int(sys.argv[1]), contentType)
      log.warn("Script finished, success!")
      xbmcplugin.endOfDirectory(int(sys.argv[1]))
